package com.leesche.zcsp.node.utils;

import org.apache.commons.beanutils.BeanUtils;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

/**
 * Created by kaider on 2016/12/6.
 * Cvs文件工具类
 */
public class CsvUtil {

    /**
     * 生成csv文件
     * @param exportData 源数据List
     * @param map csv文件的列表头map
     * @param outPutPath 文件路径
     * @param fileName 文件名称
     * @return
     */
    public static File createCsvFile(
            List exportData,
            LinkedHashMap map,
            String outPutPath,
            String fileName
    ){
        File csvFile = null;
        BufferedWriter outPutStream = null;
        try {
            File file = new File(outPutPath);
            if(!file.exists()){
                file.mkdir();
            }
            csvFile = File.createTempFile(fileName,".csv",new File(outPutPath));

            /* 创建的文件不为乱码 */
            outPutStream = new BufferedWriter(
                    new OutputStreamWriter(
                        new FileOutputStream(csvFile),"GB2312"),1024);

            /*outPutStream = new BufferedWriter(
                    new OutputStreamWriter(
                            new FileOutputStream(csvFile),"UTF-8"),1024);*/

            for(Iterator propertyIterator = map.entrySet().iterator();propertyIterator.hasNext();){
                Map.Entry propertyEntry = (Map.Entry) propertyIterator.next();
                outPutStream.write(propertyEntry.getValue().toString()!=null ? propertyEntry.getValue().toString() :"");
                if (propertyIterator.hasNext()) {
                    outPutStream.write(",");
                }
            }
            outPutStream.newLine();
            //写入内容
            for(Iterator iterator = exportData.iterator(); iterator.hasNext();) {
                Object row = iterator.next();
                for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator.hasNext(); ) {
                    Map.Entry propertyEntry = (Map.Entry) propertyIterator.next();
                    outPutStream.write(BeanUtils.getProperty(row, propertyEntry.getKey().toString()));
                    if(propertyIterator.hasNext()){
                        outPutStream.write(",");
                    }
                }
                if(iterator.hasNext()){
                    outPutStream.newLine();
                }
            }
            outPutStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } finally {
            try {
                outPutStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return csvFile;
    }

    /**
     * 创建csv文件
     * @param file
     * @param dataList
     * @return
     */
    public static boolean createCsvFile(
            File file,
            List<String> dataList
    ){
        boolean flag=false;
        FileOutputStream out=null;
        OutputStreamWriter osw=null;
        BufferedWriter bw=null;

        try {
            out = new FileOutputStream(file);
            osw = new OutputStreamWriter(out);
            bw =new BufferedWriter(osw);
            if(dataList!=null && !dataList.isEmpty()){
                for(String data : dataList) {
                    bw.append(data).append("\r");
                }
            }
            flag=true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            flag=false;
        } catch (IOException e) {
            e.printStackTrace();
            flag=false;
        }finally {
            if(bw!=null || osw!=null || out!=null){
                try {
                    bw.close();
                    osw.close();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }


    public static void main(String[] args) {
        List exportData = new ArrayList<Map>();
        Map row1 = new LinkedHashMap<String, String>();
        row1.put("1", "11");
        row1.put("2", "12");
        row1.put("3", "13");
        row1.put("4", "14");
        exportData.add(row1);
        row1 = new LinkedHashMap<String, String>();
        row1.put("1", "21");
        row1.put("2", "22");
        row1.put("3", "23");
        row1.put("4", "24");
        exportData.add(row1);
        LinkedHashMap map = new LinkedHashMap();
        map.put("1", "第一列");
        map.put("2", "第二列");
        map.put("3", "第三列");
        map.put("4", "第四列");

        String path = "D:/export/";
        String fileName = "文件导出";
        createCsvFile(exportData,map,path,fileName);
        //生成文件2
        List<String> dataList=new ArrayList<String>();
        dataList.add("1,张三,男");
        dataList.add("2,李四,男");
        dataList.add("3,小红,女");
//        boolean isSuccess=createCsvFile(new File("D:/export/2.csv"), dataList);
        boolean isSuccess=createCsvFile(new File("D:/export/2.csv"), exportData);
        System.out.println(isSuccess);
    }
}
